from cluster_qkd_networkx_cluster import OverlappingClusters, XMultiClusterQKDNetwork
import random
import time
import matplotlib.pyplot as plt
from log import clearContent
import numpy as np

read_from_txt = True

t = OverlappingClusters(read_from_txt=read_from_txt) #生成一个网络
if(not read_from_txt):
     # t.showGraph()
     listArr = t.splitNet() #划分这个网络
     print("分簇完成")
     for idx, item in enumerate(listArr):
          item.sort()
          print(f"【长度 {len(item)}】：{item}")
else:
     # t.showGraph()
     # t.showSubFig()
     map_dict = {}
     overlap_nodes = []
     for i in t.clusterListArr:
          for j in i:
               if(j not in map_dict):
                    map_dict[j] = 1
               else:
                    map_dict[j] += 1
                    overlap_nodes.append(j)
     
     # for i in t.clusterListArr:
     #      i.sort()
          # 打印分好的簇
          # print(i)
     
# 读入这个簇集合网络，并使用LP进行计算
# read_from_pkl 从pkl文件里面读 XCluster 这个类
qkdnx = XMultiClusterQKDNetwork(t.getGraph(), t.clusterListArr, read_from_pkl=True)

compareTxt = "compare.txt"
clearContent(compareTxt)

total_cplex_alphas = []
total_spf_alphas = []
total_online_greedy_alphas = []

for _ in range(20):
    end_time = time.time()

    cplex_alphas = []
    spf_alphas = []
    online_greedy_alphas = []

    for broken_edge in list(t.G.edges()):
        # 断掉一条边
        brokenStartUniqueID, brokenEndUniqueID = broken_edge[0], broken_edge[1]
        # 跑1000轮，测均值
        for i in range(1000):
            clusterNum = qkdnx.getClusterNum()
            _startClusterID = random.randint(1, clusterNum)
            _endClusterID = random.randint(1, clusterNum)
            qkdnx.requestFlow(
                startClusterID = _startClusterID, 
                startNodeID = random.randint(1, qkdnx.clusters[_startClusterID-1].nodeNum), 
                endClusterID = _endClusterID, 
                endNodeID = random.randint(1, qkdnx.clusters[_endClusterID-1].nodeNum), 
                flow = random.randint(1, 50),
                # 在有一条边破损的情况下
                brokenStartNodeID = brokenStartUniqueID,
                brokenEndNodeID = brokenEndUniqueID,
            )
        # 保留一个副本
        cplex_alphas.append(qkdnx.maxCplexAlpha)
        spf_alphas.append(qkdnx.maxSPFAlpha)
        online_greedy_alphas.append(qkdnx.maxOnlineGreedyAlpha)
        qkdnx.clearLinkLoad()
    
    # 保留一个副本
    total_cplex_alphas.append(np.mean(cplex_alphas))
    total_spf_alphas.append(np.mean(spf_alphas))
    total_online_greedy_alphas.append(np.mean(online_greedy_alphas))

with open(compareTxt, "a") as file:
        file.write(f"{np.mean(total_cplex_alphas)} {np.mean(total_spf_alphas)} {np.mean(total_online_greedy_alphas)}\n")

data = []
with open(compareTxt, "r") as file:
    for line in file:
        values = line.strip().split()
        data.append([float(values[0]), float(values[1]), float(values[2])])
x = list(range(1, len(data) + 1))
y1 = [item[0] for item in data]
y2 = [item[1] for item in data]
y3 = [item[2] for item in data]
plt.plot(x, y1, label='Cplex')  # 第一条折线，对应数据中的第一列
plt.plot(x, y2, label='Spf')  # 第二条折线，对应数据中的第二列
plt.plot(x, y2, label='OnlineGreedy')  # 第二条折线，对应数据中的第三列
plt.title('Compare：1000 Flows')
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.legend()
plt.show()